<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="证书名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择证书名称" filterable allow-create style="width: 100%" :disabled="mode === 'view'">
            <el-option v-for="item in certificateNameOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="证书编号" prop="certificate_no">
          <el-input v-model="form.certificate_no" placeholder="请输入证书编号" :disabled="mode === 'view'" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="发证机构" prop="issuing_org">
          <el-input v-model="form.issuing_org" placeholder="请输入发证机构" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="证书级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择证书级别" style="width: 100%" :disabled="mode === 'view'">
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="发证日期" prop="issue_date">
          <el-date-picker
            v-model="form.issue_date"
            type="date"
            placeholder="请选择发证日期"
            style="width: 100%"
            :disabled="mode === 'view'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="有效期至" prop="expiry_date">
          <el-date-picker
            v-model="form.expiry_date"
            type="date"
            placeholder="请选择有效期"
            style="width: 100%"
            :disabled="mode === 'view'"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="备注" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
            :disabled="mode === 'view'"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 附件列表区域始终显示 -->
    <div class="attachment-section">
      <div class="attachment-card attachment-card-with-label">
        <span class="attachment-card-label">附件列表</span>
        <div class="attachment-card-content">
          <AttachmentList
            module="certificates"
            :moduleId="form.id"
            :readonly="mode !== 'edit' && mode !== 'add'"
            @add-attachment="openUploader"
            @refresh="loadAttachments"
          />
          <el-dialog v-model="showUploader" title="上传附件" width="500px" destroy-on-close>
            <AttachmentUploader
              v-if="form.id"
              module="certificates"
              :moduleId="form.id"
              @upload-success="loadAttachments"
            />
            <div v-else style="color: #f56c6c; padding: 20px;">请先保存证书，再上传附件</div>
          </el-dialog>
        </div>
      </div>
    </div>
    <div class="dialog-footer" v-if="mode !== 'view'">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
    </div>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted, onActivated } from 'vue'
import { ElMessage } from 'element-plus'
import { certificateAPI, certificateNameAPI } from '../../api'
import { getDictItemsByCode } from '../../api/dict'
import AttachmentList from '../../components/AttachmentList.vue'
import AttachmentUploader from '../../components/AttachmentUploader.vue'

const props = defineProps({
  mode: { type: String, default: 'view' }, // 'add' | 'edit' | 'view'
  certificate: { type: Object, default: () => ({}) },
  employeeId: { type: [String, Number], default: null },
  visible: { type: Boolean, default: false }
})
const emit = defineEmits(['refresh', 'close'])

const formRef = ref(null)
const submitting = ref(false)
const form = ref({
  id: null,
  name: '',
  certificate_no: '',
  level: '',
  issuing_org: '',
  issue_date: '',
  expiry_date: '',
  description: ''
})

const rules = {
  name: [ { required: true, message: '请输入证书名称', trigger: 'blur' } ],
  certificate_no: [ { required: true, message: '请输入证书编号', trigger: 'blur' } ],
  issuing_org: [ { required: true, message: '请输入发证机构', trigger: 'blur' } ],
  issue_date: [ { required: true, message: '请选择获得日期', trigger: 'change' } ]
}

const certificateNameOptions = ref([])
const lastName = ref('')

const attachments = ref([])
const attachmentsLoading = ref(false)
const showUploader = ref(false)

const levelOptions = ref([])

const loadAttachments = async () => {
  if (!form.value.id) return
  attachmentsLoading.value = true
  try {
    const res = await certificateAPI.getAttachments(form.value.id)
    attachments.value = res.data
  } catch (e) {
    attachments.value = []
  } finally {
    attachmentsLoading.value = false
  }
}

const loadCertificateNames = async () => {
  try {
    const res = await certificateNameAPI.getAll(1, 1000, {})
    // 兼容后端直接返回数组或 {data: [...]} 两种情况
    const arr = Array.isArray(res.data) ? res.data : (res.data.data || [])
    certificateNameOptions.value = arr.map(item => ({
      label: item.name + (item.level ? `（${item.level}）` : ''),
      value: item.name,
      issuing_org: item.issuing_org
    }))
  } catch (e) {
    certificateNameOptions.value = []
  }
}

watch(() => props.certificate, (val) => {
  if (val) {
    Object.assign(form.value, val)
    lastName.value = val.name || ''
    const selected = certificateNameOptions.value.find(item => item.value === form.value.name)
    if (selected && selected.issuing_org) {
      form.value.issuing_org = selected.issuing_org
    } else {
      form.value.issuing_org = ''
    }
    if (val.id) {
      loadAttachments()
    }
  }
}, { immediate: true })

watch(
  () => form.value.name,
  (newName) => {
    const selected = certificateNameOptions.value.find(item => item.value === newName)
    if (selected && selected.issuing_org) {
      form.value.issuing_org = selected.issuing_org
    } else {
      form.value.issuing_org = ''
    }
  }
)

watch(
  () => props.visible,
  (val) => {
    if (val) {
      loadCertificateNames()
    }
  }
)

function formatDateToYMD(val) {
  if (!val) return undefined
  if (typeof val === 'string') {
    if (val.includes('T')) return val.split('T')[0]
    return val
  }
  if (val instanceof Date) {
    const y = val.getFullYear()
    const m = String(val.getMonth() + 1).padStart(2, '0')
    const d = String(val.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  return undefined
}

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const payload = { ...form.value }
        const formattedIssueDate = formatDateToYMD(payload.issue_date)
        const formattedExpiryDate = formatDateToYMD(payload.expiry_date)
        if (formattedIssueDate) {
          payload.issue_date = formattedIssueDate
        } else {
          delete payload.issue_date
        }
        if (formattedExpiryDate) {
          payload.expiry_date = formattedExpiryDate
        } else {
          delete payload.expiry_date
        }
        if (props.mode === 'add') {
          await certificateAPI.create({ ...payload, employee_id: props.employeeId })
          ElMessage.success('新增成功')
        } else if (props.mode === 'edit') {
          await certificateAPI.update(payload.id, payload)
          ElMessage.success('更新成功')
        }
        emit('refresh')
        emit('close')
      } catch (error) {
        ElMessage.error(props.mode === 'add' ? '新增证书失败' : '更新证书失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

watch(() => form.value.id, (val) => {
  if (val) loadAttachments()
})

function openUploader() {
  if (!form.value.id) {
    ElMessage.warning('请先保存证书，再上传附件')
    return
  }
  showUploader.value = true
}

onMounted(() => {
  loadCertificateNames()
  getDictItemsByCode('CERT_LEVEL').then(res => {
    levelOptions.value = res.data
  })
})

onActivated(() => {
  loadCertificateNames()
})
</script>

<style scoped>
.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #dcdfe6;
}
.attachment-section {
  display: flex;
  flex-direction: column;
  margin-top: 24px;
}
.attachment-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
}
:deep(.attachment-list) {
  display: flex;
  flex-direction: column;
}
.attachment-card {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}
.attachment-card-label {
  position: absolute;
  top: -12px;
  left: 16px;
  background: #fff;
  color: #409EFF;
  font-size: 15px;
  font-weight: 500;
  padding: 0 10px;
  z-index: 2;
  border-radius: 8px 8px 8px 0;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.04);
  letter-spacing: 2px;
}
.attachment-card-with-label {
  position: relative;
  margin-top: 16px;
}
.attachment-card-content {
  display: flex;
  flex-direction: column;
}
</style> 